package com.rc.saas.mini.service.elec;

import com.rc.saas.mini.common.constant.WebConstant;
import com.rc.saas.mini.mapper.elec.ElecGunMapper;
import com.rc.saas.mini.model.elec.ElecGun;
import com.rc.saas.mini.model.elec.ElecGunExample;
import com.rc.saas.mini.model.elec.ElecPile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author wangzhengwei
 * @create 2021/12/18
 */
@Service
public class ElecGunServiceImpl implements ElecGunService {
    @Autowired
    private ElecGunMapper elecGunMapper;

    @Override
    public ElecGunMapper getMapper() {
        return elecGunMapper;
    }


    @Override
    public ElecGun selectByQrCode(String qrCode) {
        ElecGunExample example = new ElecGunExample();
        example.createCriteria().andHlhtGunQrcodeEqualTo(qrCode);
        return elecGunMapper.selectByExample(example).stream().findFirst().orElseGet(() -> null);
    }

    @Override
    public ElecGun selectByGunNo(String gunNo) {
        ElecGunExample example = new ElecGunExample();
        example.createCriteria().andGunNoEqualTo(gunNo);
        return elecGunMapper.selectByExample(example).stream().findFirst().orElseGet(() -> null);
    }

    @Override
    public ElecGun selectGunByGunNo(String gunNo) {
        ElecGunExample elecGunExample = new ElecGunExample();
        elecGunExample.createCriteria().andGunNoEqualTo(gunNo);
        List<ElecGun> elecGuns = elecGunMapper.selectByExample(elecGunExample);
        if (elecGuns != null && elecGuns.size() > 0) {
            return elecGuns.get(0);
        } else {
            return null;
        }
    }

    @Override
    public List<ElecGun> listGunByStationId(Long elecStationId) {
        ElecGunExample elecGunExample = new ElecGunExample();
        elecGunExample.createCriteria().andElecStationIdEqualTo(elecStationId).andOperateStatusEqualTo(WebConstant.CON1);
        elecGunExample.setOrderByClause("sort_num");
        return elecGunMapper.selectByExample(elecGunExample);
    }

    @Override
    public ElecGun validGun(ElecPile pile, String gunNum) {
        ElecGunExample gunExample = new ElecGunExample();
        gunExample.createCriteria().andElecPileIdEqualTo(pile.getElecPileId());
        List<ElecGun> guns = elecGunMapper.selectByExample(gunExample);
        if (CollectionUtils.isEmpty(guns)) {
            return null;
        }

        if (gunNum.length() > 1) {
            gunNum = gunNum.substring(1);
        }
        for (ElecGun g : guns) {
            if (g.getGunNum().endsWith(gunNum)){
                return g;
            }
        }
        return null;
    }
}
